package net.hserver.gateway.core.strategy.imp;

import net.hserver.gateway.core.strategy.Chose;
import net.hserver.gateway.core.strategy.ServerNode;

import java.util.ArrayList;
import java.util.List;

/**
 * 加权轮询
 *
 * @author hxm
 */
public class WeightPollingStrategy<T> implements Chose<T> {

    private List<ServerNode> hosts;

    private static WeightPollingStrategy weightPollingStrategy;

    private WeightPollingStrategy() {
    }

    @Override
    public synchronized T choseInfo(String ip) {
        int tempWeight = -1;
        ServerNode tempServerNode = null;
        //检查是否都需要初始
        boolean flag = true;
        for (ServerNode host : hosts) {
            if (host.getCurrentWeight() != 0) {
                flag = false;
            }
        }
        /**
         * 进行初始化
         */
        if (flag) {
            for (ServerNode host : hosts) {
                if (host.getCurrentWeight() <= 0) {
                    host.setCurrentWeight(host.getWeight());
                }
            }
        }
        /**
         * 选择数据
         */
        for (ServerNode host : hosts) {
            if (host.getCurrentWeight() > tempWeight) {
                tempWeight = host.getCurrentWeight();
                tempServerNode = host;
            }
        }
        tempServerNode.setCurrentWeight(tempWeight - 1);
        return (T) tempServerNode;
    }

    public static <T> WeightPollingStrategy getInstance(List<T> hosts) {
        if (weightPollingStrategy == null) {
            synchronized (RandomStrategy.class) {
                if (weightPollingStrategy == null) {
                    weightPollingStrategy = new WeightPollingStrategy();
                }
            }
        }
        weightPollingStrategy.hosts = hosts;
        return weightPollingStrategy;
    }


    public static void main(String[] args) {

        ArrayList<ServerNode> serverNodes = new ArrayList<>();
        for (int i = 0; i < 2; i++) {
            ServerNode serverNode = new ServerNode();
            serverNode.setWeight(i + 1);
            serverNodes.add(serverNode);
        }
        WeightPollingStrategy instance = getInstance(serverNodes);
        new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                Object o = instance.choseInfo(null);
            }
        }).start();

        new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                Object o = instance.choseInfo(null);
            }
        }).start();

    }


}
